#include <windows.h>
#include <stdlib.h>
#include "api.h"

PVOID apiNew(int len){
	PVOID data = malloc(len);
	memset(data, 0, len);	
	return data;
}

void apiFree(PVOID data){
	free(data);
}

PVOID apiRegisterData(HWND hwnd, UINT message, LPARAM lParam){
	PVOID wndData;
	if (message==WM_NCCREATE)
    {
        LPCREATESTRUCT lpCS = (LPCREATESTRUCT)lParam;
        wndData = (PVOID)lpCS->lpCreateParams;
        SetWindowLong( hwnd, GWL_USERDATA, (ULONG)wndData);
    }
    else
    {
        wndData = (PVOID)GetWindowLong(hwnd, GWL_USERDATA);
    }
	return wndData;
}

void apiBitmap(HDC pdc, HBITMAP bmp, int x, int y){
	BITMAP logBitmap;

	GetObject(bmp, sizeof(BITMAP), &logBitmap);
	
	HDC mdc = CreateCompatibleDC(pdc);
	SelectObject(mdc, bmp);
	BitBlt(pdc, x, y, logBitmap.bmWidth, logBitmap.bmHeight, mdc, 0, 0, SRCCOPY);
	DeleteDC(mdc);
}

void apiOnPaint(HWND hwnd, FUNC_PAINT paintFunction, VOID *data){
	PAINTSTRUCT ps;
	HDC mdc = BeginPaint(hwnd, &ps);
	
	paintFunction(hwnd, mdc, data);

	EndPaint(hwnd, &ps);
}

int apiRegisterControlWnd(HINSTANCE instancia, char *className, WNDPROC wndProc)
{
    WNDCLASSEX wincl;
	memset(&wincl, 0, sizeof(WNDCLASSEX));

	wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
    wincl.hInstance = instancia;
    wincl.lpszClassName = className;
    wincl.lpfnWndProc = wndProc;
    wincl.style = CS_DBLCLKS;
    wincl.cbSize = sizeof (WNDCLASSEX);    
	wincl.hbrBackground = CreateSolidBrush(0xC0C0C0);
    if (!RegisterClassEx (&wincl))
        return 0;
    return TRUE;
}

int apiRegisterMainWnd(HINSTANCE instancia, char *szClassName, WNDPROC mainWndProc, UINT menuId){
	
    WNDCLASSEX wincl;
	memset(&wincl, 0, sizeof(WNDCLASSEX));

    wincl.hInstance = instancia;
    wincl.lpszClassName = szClassName;
    wincl.lpfnWndProc = mainWndProc;
    wincl.style = CS_DBLCLKS;
    wincl.cbSize = sizeof (WNDCLASSEX);

    wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
    wincl.lpszMenuName = NULL;
    wincl.cbClsExtra = 0;
    wincl.cbWndExtra = 0;
    wincl.hbrBackground = NULL;
	wincl.lpszMenuName = MAKEINTRESOURCE(menuId);

    if (!RegisterClassEx (&wincl))
        return 0;
    return TRUE;
}
